/****************
 *@description: 库存管理  procurement/stockTake/index
 *@author: Xhd
 *@date: 2023-07-24 16:41:25
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import { Select, Button } from "antd";
import { apiStockTakeListAddBefore, apiStockLibraryGoodsPage, apiStockLibraryGoodsActivityWait, apiStockLibraryGoodsList } from '@/request/procurement/stock.js';
import store from "@/store/store";
import { exportSheetTable } from '@/utils/exportTable';

const { Option } = Select

class Stock extends Component {
  constructor() {
    super()
    this.queryFormRef_store = React.createRef()
    this.state = {
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          render: (text, record, index) => {
            return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
          }
        },
        {
          title: "仓库名称",
          dataIndex: "libraryName",
          key: "libraryName",
        },
        {
          title: "物料编码",
          dataIndex: "goodsSkuNo",
          key: "goodsSkuNo",
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          key: 'materialName'
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
        },
        {
          title: "规格",
          dataIndex: "sku",
          key: "sku",
        },
        {
          title: "库存下限",
          dataIndex: "minCount",
          key: "minCount",
          render: (text) => {
            if (text == -1) {
              return '不限制'
            }
            return text
          }
        },
        {
          title: "上下架",
          dataIndex: "goodsStatus",
          key: "goodsStatus",
          render: (text) => {
            switch (text) {
              case 'Y':
                return "上架"
              case 'N':
                return "下架"
              case 'G':
                return "管理员下架"
              default:
                return '/'
            }
          }
        },
        {
          title: "库存量",
          dataIndex: "count",
          key: "count",
        },
        {
          title: "待出库",
          dataIndex: "waiteOutCount",
          key: "waiteOutCount",
          render: (text, record) => {
            return <Button type="link" >{text}</Button>
            return <Button type="link" onClick={() => this.onViewZhanYong(record)}>{text}</Button>
          }
        },
        {
          title: "操作",
          dataIndex: "serviceShowFile",
          key: "serviceShowFile",
          fixed: 'right',
          render: (text, render) => {
            return <div>
              <TheButton haspermi={['storage:stockStore:view']} onClick={() => this.goGoods(render.id)}>查看详情</TheButton>
            </div>
          }
        },
      ],
      searchOption: [
        { field: 'libraryId', label: '仓库名称', placeholder: '请选择仓库名称', required: false, rules: [], type: 'Select', txt: 'name', value: 'id', options: [], defaultValue: '' },
        {
          field: 'goodsStatus', label: '上架状态', placeholder: '请选择上架状态', required: false, rules: [], type: 'Select', options: [
            { label: "上架", value: "Y" }, { label: "下架", value: "N" }
          ], defaultValue: ''
        },
        { field: 'materialId', label: '物料ID', placeholder: '请输入物料ID', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'goodsName', label: '物料名称', placeholder: '请输入物料名称', required: false, rules: [], type: 'Input', defaultValue: '' },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      newColumns_store: [],
      form_show_store: true,
      totalStore: 0,
    }
  }

  componentDidMount() {
    this.setState({
      newColumns_store: this.state.columns
    })
    let searchParams = store.getState().searchValue
    let { queryForm_store, pageNo, pageSize, pathName } = searchParams
    this.queryFormRef_store.onSetDefault({
      ...queryForm_store
    })
    if (searchParams && pathName === 'stock') {
      this.setState({
        queryForm_store,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        },
      }, () => {
        this.getLibrarys()
        this.getPage()
      })
    } else {
      this.getLibrarys()
      this.getPage()
    }
  }

  getLibrarys() {
    apiStockTakeListAddBefore().then(res => {
      this.state.searchOption[0].options = res.data.librarys
      this.setState({
        librarys: res.data.librarys,
        searchOption: this.state.searchOption
      })
    })
  }

  getPage(values) {
    this.setState({
      queryForm_store: values === undefined ? this.state.queryForm_store : { ...values }
    }, async () => {
      let { pageNo, pageSize } = this.state.pageData
      let params = {
        pageNo: this.state.pageData.pageNo,
        pageSize: this.state.pageData.pageSize,
        queryForm_store: this.state.queryForm_store,
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'stock',
          ...params
        }
      })
      let res = await apiStockLibraryGoodsPage({ pageNo, pageSize, ...this.state.queryForm_store })
      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          totalStore: res.totalCount
        })
      }
    })
  }

  onViewZhanYong(record) {
    apiStockLibraryGoodsActivityWait({ libraryGoodsId: record.id }).then(res => {
      if (res.code === 0) {
        alert(res.data)
      }
    })
  }

  goGoods(id) {
    this.props.history.push('/procurement/stockTake/goodsStore/' + id)
  }

  rowClassName(record, index) {
    if (record.minCount > record.count) {
      return 'warning'
    }
    return ''
  }

  onFormSearch_store(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getPage(values)
    })
  }

  onReset_store = () => {
    this.setState({
      queryForm_store: {}
    }, () => {
      this.pageChangeStore(1, 10)
    })
  }

  pageChangeCheck = (pageNo, pageSize) => {
    this.setState({
      pageDataCheck: {
        pageNo, pageSize
      }
    }, () => {
      this.getCheckPage()
    })
  };

  pageChangeStore = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getPage()
    })
  };

  getGoodsStatus = (value) => {
    switch (value) {
      case 'Y':
        return "上架"
      case 'N':
        return "下架"
      case 'G':
        return "管理员下架"
      default:
        return '/'
    }
  }

  export = async () => {
    let tH_data, tB_data
    tH_data = [
      { prop: 'id', title: 'id' },
      { prop: 'libraryName', title: '仓库名称' },
      { prop: 'goodsSkuNo', title: '物料编码' },
      { prop: 'materialName', title: '物料名称' },
      { prop: 'goodsName', title: '物品名称' },
      { prop: 'goodsName', title: '物料名称' },
      { prop: 'sku', title: '规格' },
      { prop: 'goodsStatus', title: '上架状态' },
      { prop: 'minCount', title: '库存下限', valueType: 'number' },
      { prop: 'count', title: '库存量', valueType: 'number' },
      { prop: 'waiteOutCount', title: '待出库', valueType: 'number' },
      { prop: 'sps', title: '实盘数', valueType: 'number' },
    ]
    let values = this.state.queryForm_store
    console.log(values);
    let res = await apiStockLibraryGoodsList({ "goodsName": values && values.goodsName ? values.goodsName : '', libraryId: values && values.libraryId ? values.libraryId : '', materialId: values && values.materialId ? values.materialId : "", goodsStatus: values && values.goodsStatus ? values.goodsStatus : "" })
    if (res.code === 0 && res.data && res.data.length > 0) {
      tB_data = res.data.map(item => {
        return {
          ...item,
          goodsStatus: this.getGoodsStatus(item.goodsStatus),
          minCount: item.minCount == -1 ? '不限制' : item.minCount,
          row_bgColor: item.count < item.minCount ? '#e8b300' : '',
          sps: ''
        }
      })
      exportSheetTable({
        fileName: '库存管理', tH_data, tB_data: tB_data, isSheet: true, merge: false
      })
    }
  }

  render() {
    const { newColumns_store, columns, form_show_store, searchOption, dataSource, pageData, totalStore } = this.state
    return (<div className="p-layout-box commodity-examine">
      <TheQueryForm ref={(ref) => this.queryFormRef_store = ref} show={form_show_store} option={searchOption}
        onReset={() => this.onReset_store()}
        onGetValues={(values) => this.onFormSearch_store(values)} >
      </TheQueryForm>
      <TheTableExtend
        columns={columns}
        onFormTrigger={() => this.setState({ form_show_store: !this.state.form_show_store })}
        onTableRefresh={() => this.getPage()}
        onColumnsFilter={(value) => this.setState({
          newColumns_store: value
        })}
      >
        <TheButton type="default" size="middle" haspermi={['storage:stockStore:export']} onClick={this.export}>库存导出</TheButton>
      </TheTableExtend>
      <TheTable
        scroll={{ x: "max-content", y: '53vh' }}
        columns={newColumns_store}
        rowClassName={(record, index) => this.rowClassName(record, index)}
        dataSource={dataSource}
      />
      <ThePagination
        pageNo={pageData.pageNo}
        pageSize={pageData.pageSize}
        total={totalStore}
        pageChange={this.pageChangeStore}
      />
    </div>)
  }
}

export default Stock
